import { createRefund } from "../../utils/pay/wxpay-partner";
import { api } from "./api";

export async function onRefund(body, userId, notify_url) {
  if (!body.id) {
    throw "缺少参数";
  }
  const row = await api.getOrder(body.id);
  if (!row || row.userId != userId) {
    throw "订单不存在";
  }
  if (row.status != 1) {
    throw "订单状态已变化";
  }
  const shop = await api.getShopRow(row.sid);
  if (!shop || !shop.mch_id) {
    throw "未查到商户号";
  }
  const total = row.total_price * 100;
  const data = await createRefund({
    sub_mchid: shop.mch_id,
    out_trade_no: row.order_no,
    out_refund_no: row.order_no + "_1",
    reason: "用户退款",
    notify_url,
    amount: {
      refund: total,
      total,
      currency: "CNY",
    },
  });
  await api.postOrder({
    id: row.id,
    status: 6,
  });
  return data;
}
